<script setup lang="ts">
import Category from '@/views/Product/Attr/components/category.vue'
import { ref, toRefs, watch, computed, nextTick, onBeforeUnmount } from "vue";
// 引入分类id之后的属性值管理接口
import { reqAtttAPI, reqAddOrUpdateAttrAPI, reqDeleteAttrAPI } from '@/apis/product/attr';
import type { AttrResponseData, Attr, AttrValue } from '@/apis/product/attr/type'
import { ElMessage } from 'element-plus'
import useCategoryStore from '@/store/modules/category';
const categoryStore = useCategoryStore()

//三级分类商品属性数据列表
const attrList = ref<Attr[]>([])
//收集新增属性值数据
const addAttrParmas = ref<Attr>({
    attrName: '',//属性名称
    attrValueList: [],//属性值列表
    categoryId: '',//三级分类id
    categoryLevel: 3//三级分类
})

// 监听仓库三级分类id
watch(() => categoryStore.c3Id, () => {
    //清空上一次查询的属性与属性值
    attrList.value = []
    //确保有了三级分类id才发请求
    if (!categoryStore.c3Id) return
    getAttrList()
})
//获取属性值列表
const getAttrList = async () => {
    //获取分类的id
    const { c1Id, c2Id, c3Id } = toRefs(categoryStore)
    const result: AttrResponseData = await reqAtttAPI(c1Id.value, c2Id.value, c3Id.value)
    if (result.code === 200) {
        attrList.value = result.data
    }
}
//定义添加属性值页面变化
const show = ref<number>(1)
//页面添加平台属性按钮点击回调函数
const addAttr = () => {
    //点击时先清空一下添加属性值页面的数据
    Object.assign(addAttrParmas.value, {
        attrName: '',
        categoryId: categoryStore.c3Id,
        categoryLevel: 3,
        attrValueList: []
    })
    show.value = 0
}
//点击页面编辑按钮点击回调函数
const updataAttr = (row: Attr) => {
    show.value = 0
    //将已有的属性对象给addAttrParmas赋值 要深拷贝赋值
    Object.assign(addAttrParmas.value, JSON.parse(JSON.stringify(row)))
}
//点击页面删除按钮点击回调函数
const deleteAttr = async (attrId: number) => {
    //点击删除按钮后，发送删除属性接口
    const result: any = await reqDeleteAttrAPI(attrId)
    if (result.code === 200) {
        ElMessage.success('删除成功')
        getAttrList()
    } else {
        ElMessage.error('删除失败')
    }

}

//点击页面添加平台属性值之后



//添加属性值页面添加属性值按钮点击回调函数
const addAttrValue = () => {
    //点击添加属性值按钮后，给attrParams数组添加一个属性值对象
    addAttrParmas.value.attrValueList.push({
        valueName: '',
        flag: true
    })
    //获取最后一个el-input聚焦
    nextTick(() => {
        inputRefs.value[inputRefs.value.length - 1].focus()
    })
}
//添加属性值页面取消按钮点击回调函数
const closeAttr = () => {
    show.value = 1
}
//计算保存属性值按钮是否可用
const isSaveEnabled = computed(() => {
    return (
        addAttrParmas.value.attrName.trim() !== '' &&
        addAttrParmas.value.attrValueList.length > 0 &&
        addAttrParmas.value.attrValueList.some(item => item.valueName?.trim() !== '')
    )
})
//点击页面保存按钮点击回调函数
const save = async () => {
    //发送添加属性值接口
    const result: any = await reqAddOrUpdateAttrAPI(addAttrParmas.value)
    if (result.code === 200) {
        //添加成功
        //提示
        ElMessage.success(addAttrParmas.value.id ? '修改成功' : '添加成功')
        //关闭添加属性值页面
        show.value = 1
        //重新获取属性值列表
        getAttrList()
    } else {
        ElMessage.error(addAttrParmas.value.id ? '修改失败' : '添加失败')
        show.value = 1
    }
}
//定义el-input和div的切换查看状态
const flag = ref<boolean>(true)
//el-input失去焦点事件
const toLook = (row: AttrValue, $index: number) => {
    //内容不能为空
    if (row.valueName.trim().length == 0) {
        addAttrParmas.value.attrValueList.splice($index, 1)
        ElMessage.warning('属性值不能为空')
        return
    }
    //内容不能重复
    for (let i = 0; i < addAttrParmas.value.attrValueList.length; i++) {
        if (i != $index && addAttrParmas.value.attrValueList[i].valueName == row.valueName) {
            addAttrParmas.value.attrValueList.splice($index, 1)
            ElMessage.warning('属性值不能重复')
            return
        }
    }
    row.flag = false
}
//准备一个数组储存el-input实例
const inputRefs = ref<HTMLElement[]>([])
//页面el-input和div的div点击事件
const toEdit = (row: AttrValue, $index: number) => {
    row.flag = true
    //表单聚焦功能
    nextTick(() => {
        inputRefs.value[$index]?.focus()  // 直接聚焦对应索引的 input
    })
}
//table列的删除按钮功能
const deleteAttrValue = (row: AttrValue, $index: number) => {
    addAttrParmas.value.attrValueList.splice($index, 1)
}

//路由组件销毁的时候，仓库相关数据清空
onBeforeUnmount(() => {
    categoryStore.$patch({ c1Id: '', c2Id: '', c3Id: '' })
})
</script>
<template>
    <!-- 三级分类 -->
    <Category :show="show"></Category>
    <!-- 添加平台属性 -->
    <el-card class="attr-card-two">
        <!-- 添加属性按钮前-->
        <template v-if="show === 1">
            <el-button type="primary" icon="Plus" :disabled="!categoryStore.c3Id" @click="addAttr">添加平台属性</el-button>
            <el-table border class="box-table" :data="attrList">
                <!-- 序号列 -->
                <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
                <!-- 属性名称列 -->
                <el-table-column label="属性名称" width="200" align="center" prop="attrName">
                </el-table-column>
                <!-- 属性值名称列 -->
                <el-table-column label="属性值名称" align="center">
                    <template #="{ row }">
                        <el-tag class="tag" v-for="(item, index) in row.attrValueList" :key="item.id">{{ item.valueName
                        }}</el-tag>
                    </template>
                </el-table-column>
                <!-- 操作列 -->
                <el-table-column label="操作" width="200" align="center">
                    <template #="{ row }">
                        <el-button type="primary" icon="Edit" @click="updataAttr(row)">编辑</el-button>
                        <el-button type="danger" icon="Delete" @click="deleteAttr(row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
        <!-- 添加属性按钮后 -->
        <template v-else="show===0">
            <el-form>
                <el-form-item label="属性名称">
                    <el-input class="input-style" placeholder="请输入属性名称" v-model="addAttrParmas.attrName"></el-input>
                </el-form-item>
                <el-button type="primary" icon="Plus" :disabled="addAttrParmas.attrName ? false : true"
                    @click="addAttrValue">添加属性值</el-button>
                <el-button @click="closeAttr">取消</el-button>
                <el-table border class="box-table2" :data="addAttrParmas.attrValueList">
                    <el-table-column label="序号" width="80" alingn="center" type="index"></el-table-column>
                    <el-table-column label="属性值">
                        <template #="{ row, $index }">
                            <el-input :ref="(el: any) => { if (el) inputRefs[$index] = el }" v-if="row.flag"
                                @blur="toLook(row, $index)" @keyup.enter="toLook(row, $index)" placeholder="请输入属性值名称"
                                v-model="row.valueName"></el-input>
                            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #="{ row, $index }">
                            <el-button type="danger" icon="Delete" @click="deleteAttrValue">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" @click="save" :disabled="!isSaveEnabled">保存</el-button>
                <el-button @click="closeAttr">取消</el-button>
            </el-form>
        </template>
    </el-card>
</template>
<style lang="scss" scoped>
.attr-card-two {
    margin-top: 20px;
}

.box-table {
    margin-top: 20px;

    .tag {
        margin: 5px;
    }
}

.input-style {
    width: 240px;
}

.box-table2 {
    margin: 10px 0;
}
</style>